import 'package:flutter/material.dart';

class PickupGoods extends StatefulWidget {
  const PickupGoods({super.key});
  @override
  State<PickupGoods> createState() => _PickupGoodsState();
}

// 单选的数据源
enum SingingCharacter { lafayette, jefferson, noprint }

// 约揽类型枚举
enum CollectionType { collection, selfDelivery, selfSend }

class _PickupGoodsState extends State<PickupGoods> {
  final _formKey = GlobalKey<FormState>(); // 表单Key
  final GlobalKey<_PickupGoodsState> formKey = GlobalKey<_PickupGoodsState>();
  SingingCharacter? _character = SingingCharacter.lafayette;
  CollectionType? _collectionType = CollectionType.collection;
  // 列表
  final List<Map<String, dynamic>> _data = [
    {
      'id': 1,
      'name': 'Ahdhhfhhhhdhhfhfhh',
      'age': 25,
      'department': '技术部',
      'salary': 15000,
    },
    {'id': 2, 'name': '李四', 'age': 30, 'department': '市场部', 'salary': 12000},
    {'id': 3, 'name': '王五', 'age': 28, 'department': '人事部', 'salary': 10000},
    {'id': 4, 'name': '赵六', 'age': 35, 'department': '财务部', 'salary': 18000},
  ];

  bool _sortAscending = true;
  int _sortColumnIndex = 0;

  void _sort<T>(int columnIndex, bool ascending) {
    setState(() {
      _sortColumnIndex = columnIndex;
      _sortAscending = ascending;

      _data.sort((a, b) {
        final aValue = a.values.toList()[columnIndex];
        final bValue = b.values.toList()[columnIndex];

        if (ascending) {
          return Comparable.compare(aValue as Comparable, bValue as Comparable);
        } else {
          return Comparable.compare(bValue as Comparable, aValue as Comparable);
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('组包揽件')),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(1),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              // 收货单号
              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('组包员', isRequired: true),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),

              Row(
                children: [
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('揽件方式', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 7,
                    child: Row(
                      children: [
                        Flexible(
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Radio<SingingCharacter>(
                                value: SingingCharacter.lafayette,
                                groupValue: _character,
                                onChanged: (SingingCharacter? value) {
                                  setState(() {
                                    _character = value;
                                  });
                                },
                                materialTapTargetSize:
                                    MaterialTapTargetSize.shrinkWrap,
                              ),
                              Flexible(child: Text('大包')),
                            ],
                          ),
                        ),
                        Flexible(
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Radio<SingingCharacter>(
                                value: SingingCharacter.jefferson,
                                groupValue: _character,
                                onChanged: (SingingCharacter? value) {
                                  setState(() {
                                    _character = value;
                                  });
                                },
                                materialTapTargetSize:
                                    MaterialTapTargetSize.shrinkWrap,
                              ),
                              Flexible(child: Text('批次')),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('约揽类型', isRequired: false),
                    ),
                  ),
                  Expanded(
                    flex: 7,
                    child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Row(
                        children: [
                          Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Radio<CollectionType>(
                                value: CollectionType.collection,
                                groupValue: _collectionType,
                                onChanged: (CollectionType? value) {
                                  setState(() {
                                    _collectionType = value;
                                  });
                                },
                                materialTapTargetSize:
                                    MaterialTapTargetSize.shrinkWrap,
                              ),
                              Text('揽收'),
                            ],
                          ),
                          Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Radio<CollectionType>(
                                value: CollectionType.selfDelivery,
                                groupValue: _collectionType,
                                onChanged: (CollectionType? value) {
                                  setState(() {
                                    _collectionType = value;
                                  });
                                },
                                materialTapTargetSize:
                                    MaterialTapTargetSize.shrinkWrap,
                              ),
                              Text('自送'),
                            ],
                          ),
                          Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Radio<CollectionType>(
                                value: CollectionType.selfSend,
                                groupValue: _collectionType,
                                onChanged: (CollectionType? value) {
                                  setState(() {
                                    _collectionType = value;
                                  });
                                },
                                materialTapTargetSize:
                                    MaterialTapTargetSize.shrinkWrap,
                              ),
                              Text('自寄'),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              // 收货单号
              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('大包重量kg:80.00', isRequired: true),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('小包数量:80/10', isRequired: true),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),

              // // 添加数据表格展示
              // Padding(
              //   padding: EdgeInsets.all(0),
              //   child: Text(
              //     '包裹详情',
              //     style: TextStyle(
              //       fontSize: 18,
              //       fontWeight: FontWeight.bold,
              //       color: Colors.blue[700],
              //     ),
              //   ),
              // ),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: _showTable(
                  _sortColumnIndex,
                  _sortAscending,
                  _sort,
                  _data,
                ),
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: DecoratedBox(
        decoration: BoxDecoration(color: const Color.fromARGB(255, 77, 76, 76)),
        child: SizedBox(
          width: double.infinity,
          height: 50,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: OutlinedButton(
                      onPressed: () {
                        // 取消操作，重置表单
                        // _resetForm();
                        // final formState = context
                        //     .findAncestorStateOfType<IncomingGoodsFormState>();
                        // formState?._resetForm();
                      },
                      style: OutlinedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.grey[600],
                        side: BorderSide.none,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 1,
                      ),
                      child: const Text('清除'),
                    ),
                  ),
                ),
                const SizedBox(width: 12),

                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: ElevatedButton(
                      onPressed: () {
                        // final formState = context
                        //     .findAncestorStateOfType<IncomingGoodsFormState>();
                        // formState?._submitForm();

                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: Text('确认提交'),
                            content: Text('是否确认提交？'),
                            actions: [
                              TextButton(
                                onPressed: () =>
                                    Navigator.of(context).pop(false),
                                child: const Text('取消'),
                              ),
                              TextButton(
                                onPressed: () {
                                  // _submitForm();
                                  Navigator.of(context).pop(false);
                                },
                                child: const Text('确认'),
                              ),
                            ],
                          ),
                        );
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue[600],
                        foregroundColor: Colors.white,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 3,
                        // shadowColor: Colors.blue.withOpacity(0.3),
                      ),
                      child: const Text('提交'),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // table展示
  Widget _showTable(
    int sortColumnIndex,
    bool sortAscending,
    void Function(int, bool) sort,
    List<Map<String, dynamic>> data,
  ) {
    return SizedBox(
      child: DataTable(
        border: TableBorder(
          horizontalInside: BorderSide(
            color: Colors.grey[300]!,
            width: 1,
          ),
        ),
       
        sortColumnIndex: sortColumnIndex,
        sortAscending: sortAscending,
        columns: [
          // DataColumn(
          //   label: SizedBox(width: 30, child: Text('序号')),
          //   // onSort: sort,
          // ),
          DataColumn(
            label: SizedBox(width: 100, child: Text('订单号/参考号')),
            // onSort: sort,
          ),
          DataColumn(
            label: SizedBox(width: 80, child: Text('重量kg')),
            // onSort: sort,
          ),
          DataColumn(label: SizedBox(width: 60, child: Text('操作'))),
        ],
        rows: data.asMap().entries.map((entry) {
          // int index = entry.key + 1;
          Map<String, dynamic> item = entry.value;
          return DataRow(
            cells: [
              // DataCell(SizedBox(width: 40, child: Text('$index'))),
              DataCell(
                SizedBox(
                  width: 100,
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Expanded(
                          
                            child: Text(
                              '${item['id']}-${item['name']}',
                              softWrap: true,
                              overflow: TextOverflow.visible,
                              maxLines: 1,
                            ),
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              '${item['id']}-${item['name']}',
                              softWrap: true,
                              overflow: TextOverflow.visible,
                              maxLines: 1,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
              DataCell(
                SizedBox(
                  width: 80,
                  child: Text('${(item['age'] * 0.5).toStringAsFixed(1)}'),
                ),
              ),
              DataCell(
                SizedBox(
                  width: 60,
                  child: GestureDetector(
                    onTap: () {
                      // 删除操作
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('删除包裹 ${item['name']}'),
                          duration: Duration(seconds: 1),
                        ),
                      );
                    },
                    child: Text(
                      '删除',
                      style: TextStyle(
                        color: Colors.red,
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          );
        }).toList(),
      ),
    );
  }
}

// 构建标签文本
Widget _buildLabel(String text, {bool isRequired = false}) {
  return SizedBox(
    // width: 200,
    child: Padding(
      padding: EdgeInsets.symmetric(horizontal: 2),
      child: Text(
        text,
        style: TextStyle(
          fontWeight: FontWeight.w500,
          fontSize: 16,
          color: isRequired ? Colors.red : Colors.grey[700],
        ),
      ),
    ),
  );
}

// 构建输入框装饰
InputDecoration _buildInputDecoration({
  required String hintText,
  required TextEditingController controller,
  Widget? suffixIcon,
}) {
  print('controller ${controller.text}');
  return InputDecoration(
    hintText: hintText,
    contentPadding: EdgeInsets.zero, // 设置上下左右内边距都为0
    // prefixIcon: Icon(prefixIcon, color: Colors.grey[600]),
    suffixIcon: suffixIcon,
    hintStyle: TextStyle(color: Colors.grey[500]),
    // isDense: true 属性用于减少输入框的垂直高度，使其更紧凑
    // 当设置为 true 时，会减少内边距，让输入框看起来更小更密集
    // 适用于需要节省空间或创建更紧凑布局的场景
    // isDense: true,
    filled: true,
    fillColor: Colors.grey[50],

    // suffixIcon: controller.text.isNotEmpty
    //             ? IconButton(
    //                 icon: Icon(Icons.clear, size: 20),
    //                 onPressed: () {
    //                   controller.clear();
    //                   // 需要通知父组件状态更新
    //                   if (mounted) {
    //                     setState(() {});
    //                   }
    //                 },
    //               )
    //             : null,
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.grey[300]!),
    ),
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.grey[300]!),
    ),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.blue, width: 2),
    ),
    errorBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.red),
    ),
    focusedErrorBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.red, width: 2),
    ),
  );
}
